<template>
  <ScrollContainer class="pr-4" v-loading="loading" :loading-tip="t('common.loadingText')">
    <div class="flex justify-around w-1/3 m-auto mb-2" v-if="isSelected">
      <!-- <a-button @click="handleResetFields">重置</a-button> -->
      <a-button type="primary" @click="customSubmitFunc" class="ml-2">保存</a-button>
    </div>
    <BasicForm @register="registerForm" v-show="isSelected">
      <template #ActionApplicantSelMode="{ model, field }">
        <RadioButtonGroup
          :options="ActionApplicantSelModeOptions"
          v-model:value="model[field]"
          @change="handleChangeActionApplicantSelScope"
        />
      </template>
      <template #ActionApplicantSelScope="{ model, field }">
        <FormItemRest>
          <RadioButtonGroup
            :options="actionApplicantSelScopeOptions"
            v-model:value="model[field]"
            @change="handleChangeActionApplicantSelScope"
          />
          <div class="mt-2" v-if="model[field] == '1'">
            <div>
              <Button type="primary" @click="handleSelectUserAdd">
                <template #icon>
                  <UserOutlined />
                </template>
                添加人员
              </Button>
            </div>
            <div class="flex gap-2 flex-wrap mt-2">
              <Button v-for="(item, index) in dataRef['ActionApplicantAssignedUsers']" :key="index">
                {{ item.realName }}
                <CloseOutlined @click.stop="handleDeleteUser(item)" />
              </Button>
            </div>
          </div>
          <div class="mt-2" v-if="model[field] == '2'">
            <Select
              placeholder="请选择角色"
              style="margin-top: 10px; width: 100%"
              :allow-clear="false"
              v-model:value="dataRef['ActionApplicantAssignedRoles']"
              mode="multiple"
              optionFilterProp="name"
            >
              <SelectOption v-for="item in roleMultilSelData" :key="item.code" :value="item.code">
                {{ item.name }}
              </SelectOption>
            </Select>
          </div>
        </FormItemRest>
      </template>
      <template #OfficeColorIndex="{ model, field }">
        <Select
          placeholder="请选择"
          style="margin: 10px; width: 150px"
          :allow-clear="false"
          v-model:value="model[field]"
        >
          <SelectOption v-for="item in colorList" :key="item.id" :value="item.id">
            <div
              :style="{ backgroundColor: item.color ? item.color : '#fff', textAlign: 'center' }"
            >
              {{ item.name }}
            </div>
          </SelectOption>
        </Select>
      </template>
      <template #handlePerson>
        <div class="flex flex-wrap cursor-pointer">
          <div class="mr-2 cursor-pointer hover:underline" @click="handleSelf">本人</div>
          <div class="mr-2 cursor-pointer hover:underline" @click="handleSelectRole">选择角色</div>
          <div class="mr-2 cursor-pointer hover:underline" @click="handleSelectPosition">
            选择岗位
          </div>
          <div class="mr-2 cursor-pointer hover:underline" @click="handleSelectUser">选择用户</div>
          <div
            v-if="dataRef.inDegree"
            class="mr-2 cursor-pointer hover:underline"
            @click="handleSendPerson"
            title="自动转换为发起人"
            >发起人</div
          >
          <div
            v-if="dataRef.inDegree"
            class="mr-2 cursor-pointer hover:underline"
            @click="handleSelfSelectUser"
          >
            自选用户
          </div>
          <div
            v-if="dataRef.inDegree"
            class="mr-2 cursor-pointer hover:underline"
            @click="handleMyDept"
            title="我的部门中的人员（除我之外）"
            >我的部门</div
          >
          <div
            v-if="dataRef.inDegree"
            class="mr-2 cursor-pointer hover:underline"
            @click="handleMyleader"
          >
            我的领导
          </div>
        </div>
        <Divider orientation="left" v-if="dataRef.inDegree">
          <CaretUpOutlined class="cursor-pointer" v-if="isMoreBut" @click="handleMoreBut" />
          <CaretDownOutlined class="cursor-pointer" v-else @click="handleMoreBut" />
        </Divider>
        <transition name="fade" mode="out-in" appear>
          <div class="flex flex-wrap cursor-pointer" v-if="isMoreBut && dataRef.inDegree">
            <div class="mr-2 cursor-pointer hover:underline" @click="handleMysubordinate">
              我的下属
            </div>
            <div
              class="mr-2 cursor-pointer hover:underline"
              @click="handleSelfUser"
              title="由前一用户自行指定（但需在所管理的部门范围内，同时限定部门无效）"
              >自选用户(管理)</div
            >
            <div
              class="mr-2 cursor-pointer hover:underline"
              @click="handleSelectDepart"
              title="部门管理员(拥有管理所在关联节点人员所在部门的权限)"
              >部门管理员</div
            >
            <div
              class="mr-2 cursor-pointer hover:underline"
              @click="selAction"
              title="流程中某个节点的处理人员"
            >
              所选节点上的人员
            </div>
            <div
              class="mr-2 cursor-pointer hover:underline"
              @click="selField"
              title="表单中指定的人员"
              >表单中指定的人员</div
            >
            <div
              class="mr-2 cursor-pointer hover:underline"
              @click="showNodeScript"
              title="通过脚本选择人员"
              >通过脚本选人</div
            >
            <div class="mr-2 cursor-pointer hover:underline" @click="handleAuto"> 自动节点 </div>
          </div>
        </transition>
      </template>
      <template #trFlag>
        <FormItemRest>
          <span title="允许上一节点处理者选择用户">
            <Checkbox v-model:checked="dataRef['flagSel']" @change="customSubmitFunc(false)"
              >选择用户</Checkbox
            >
          </span>
          <span title="在流程详情页中可放弃流程">
            <Checkbox v-model:checked="dataRef['flagDiscardFlow']" @change="customSubmitFunc(false)"
              >放弃流程</Checkbox
            >
          </span>
          <span>
            <Checkbox v-model:checked="dataRef['flagDelFlow']" @change="customSubmitFunc(false)"
              >删除流程</Checkbox
            >
          </span>
          <span>
            <Checkbox v-model:checked="dataRef['flagDelAttach']" @change="customSubmitFunc(false)"
              >删除附件</Checkbox
            >
          </span>
          <span>
            <Checkbox v-model:checked="dataRef['flagEditAttach']" @change="customSubmitFunc(false)"
              >编辑附件</Checkbox
            >
          </span>
          <span>
            <Checkbox v-model:checked="dataRef['flagTransfer']" @change="customSubmitFunc(false)"
              >转办流程</Checkbox
            >
          </span>
          <span title="根据条件判断走相应的分支线">
            <Checkbox v-model:checked="dataRef['flagXorRadiate']" @change="customSubmitFunc(false)"
              >条件分支</Checkbox
            >
          </span>
          <span
            title="节点有多条路径汇合，如果置为异步，则只要有其中的一条到达，节点就会被激活，否则，只有当所有路径都到达后才会继续"
          >
            <Checkbox
              v-model:checked="dataRef['flagXorAggregate']"
              @change="customSubmitFunc(false)"
              >异步聚合</Checkbox
            >
          </span>
          <span title="流程处理者可以拒绝流程，同时流程结束">
            <Checkbox v-model:checked="dataRef['flagFinishFlow']" @change="customSubmitFunc(false)"
              >拒绝流程</Checkbox
            >
          </span>
          <span title="模板套红（强制）" v-show="isInredEnabled">
            <Checkbox
              v-model:checked="dataRef['flagReceiveRevise']"
              @change="customSubmitFunc(false)"
              >模板套红</Checkbox
            >
          </span>
          <span title="加盖印章（非强制）" v-show="isInredEnabled">
            <Checkbox v-model:checked="dataRef['flagSeal']" @change="customSubmitFunc(false)"
              >加盖印章</Checkbox
            >
          </span>
          <span title="手动抄送流程表单">
            <Checkbox v-model:checked="dataRef['flagModify']" @change="customSubmitFunc(false)"
              >流程抄送</Checkbox
            >
          </span>
          <span title="同意并结束流程，可用于非开始节点">
            <Checkbox
              v-model:checked="dataRef['flagAgreeAndFinish']"
              @change="customSubmitFunc(false)"
              >结束流程</Checkbox
            >
          </span>
          <span
            title="同一节点中有多人处理时，每个人都可以立即往下提交，并且不能更改下一节点上之前被选择的用户"
          >
            <Checkbox v-model:checked="dataRef['flagXorFinish']" @change="customSubmitFunc(false)"
              >异步提交</Checkbox
            >
          </span>
          <span
            title="同一节点中有多人处理时，退回时不会忽略本节点其他人及其他节点上的待办记录，并且在处理完毕再次提交时，不能更改之前选择的用户"
          >
            <Checkbox v-model:checked="dataRef['flagXorReturn']" @change="customSubmitFunc(false)"
              >异步退回</Checkbox
            >
          </span>
          <span
            title="已阅，常用于领导操作，表示已知悉，流程不再往下流转，不影响流程其它分支的运行"
          >
            <Checkbox v-model:checked="dataRef['flagReaded']" @change="customSubmitFunc(false)"
              >已阅知悉</Checkbox
            >
          </span>
          <span title="强制撤回流程">
            <Checkbox v-model:checked="dataRef['flagForceRecall']" @change="customSubmitFunc(false)"
              >强制撤回</Checkbox
            >
          </span>
          <span title="节点处理完后仍可追加人员">
            <Checkbox v-model:checked="dataRef['flagAppendUser']" @change="customSubmitFunc(false)"
              >追加人员</Checkbox
            >
          </span>
          <span title="常用于领导在pdf文件上手写、圈阅" v-if="isCircleReadEnabled">
            <Checkbox v-model:checked="dataRef['flagCircleRead']" @change="customSubmitFunc(false)"
              >手写圈阅</Checkbox
            >
          </span>
          <span title="将上传或生成的word、pdf文件自动加注水印">
            <Checkbox v-model:checked="dataRef['flagWatermark']" @change="customSubmitFunc(false)"
              >加注水印</Checkbox
            >
          </span>
        </FormItemRest>
      </template>
      <template #trWatermarkText="{ model, field }">
        <FormItemRest>
          <div style="display: flex; align-items: center">
            <Input v-model:value="model[field]" />
            <Popover>
              <template #content>
                <div
                  :key="k.value"
                  v-for="k in formFields"
                  @click="handleClickMenu(k.value, 'watermarkText')"
                  class="cursor-pointer hover:underline"
                >
                  {{ k.label }}</div
                >
              </template>
              <DownOutlined style="margin-left: 10px" />
            </Popover>
          </div>
        </FormItemRest>
      </template>
      <template #isDelayTr>
        <FormItemRest>
          <div class="flex items-center">
            <Checkbox v-model:checked="dataRef['isDelayed']" style="width: 80px">延迟</Checkbox>
            <Input
              v-model:value="dataRef['timeDelayedValue']"
              style="width: 80px; margin-right: 8px"
              placeholder="请输整数"
            />
            <Select
              :options="timeDelayedUnitList"
              v-model:value="dataRef['timeDelayedUnit']"
              style="width: 100px"
            />
          </div>
          <Checkbox v-model:checked="dataRef['canPrivUserModifyDelayDate']"
            >前一用户可修改延迟时间</Checkbox
          >
        </FormItemRest>
      </template>
      <template #fieldWriteText="{ model, field }">
        <div>
          <InputTextArea v-model:value="model[field]" :disabled="true" :rows="5" />
          <div class="mt-2">
            <a-button
              class="ml-2"
              size="small"
              type="primary"
              @click="handleSelectFieldWriteText(1)"
            >
              选择
            </a-button>
            <a-button class="ml-2" size="small" @click="handleSuccessSelectFieldWriteTextClear(1)">
              清空
            </a-button>
          </div>
        </div>
      </template>
      <template #fieldHideText="{ model, field }">
        <div>
          <InputTextArea v-model:value="model[field]" :disabled="true" :rows="5" />
          <div class="mt-2">
            <a-button
              class="ml-2"
              size="small"
              type="primary"
              @click="handleSelectFieldWriteText(2)"
            >
              选择
            </a-button>
            <a-button class="ml-2" size="small" @click="handleSuccessSelectFieldWriteTextClear(2)">
              清空
            </a-button>
          </div>
        </div>
      </template>

      <template #imgComb>
        <a-button :type="dataRef.isImgComb ? 'primary' : 'default'" @click="handleConfiguration">
          <SettingOutlined title="配置" />
        </a-button>
      </template>
      <template #nodeScript>
        <div>
          <AceEditor
            key="nodeScript"
            v-model:modelValue="dataRef.nodeScript"
            :isReadonly="readonlyAceEditor"
            style="height: 130px"
          />
          <a-button
            class="mt-2"
            type="primary"
            @click="handleDesignIframe"
            :disabled="isScriptEditable == 2"
            >设计器</a-button
          >
        </div>
      </template>
      <template #subFlowTypeCode="{ model, field }">
        <Select
          v-model:value="model[field]"
          show-search
          placeholder="请选择流程类型"
          style="width: 100%"
          :options="childFlowList"
          :field-names="{ label: 'name', value: 'code' }"
          :filter-option="filterOption"
          allow-clear
          @change="getSubFlowTypeCode"
        />
      </template>
      <template #trMapField>
        <div class="flex">
          <div style="width: 120px">
            <div class="text-center">
              {{ isActionForm ? '上节点' : '父流程' }}
            </div>
            <div class="h-200px overflow-auto">
              <Tree
                :tree-data="isActionForm ? privNextFormFields : mockData"
                :fieldNames="{ key: 'name' }"
                v-model:selectedKeys="parentSelectedKeys"
              />
            </div>
            <div class="text-center cursor-pointer" @click="handleSetField(1)">
              {{ isActionForm ? '上节点 → 本节点' : '父 → 子' }}
            </div>
          </div>
          <div class="ml-2" style="width: 120px">
            <div class="text-center">
              {{ isActionForm ? '本节点' : '子流程' }}
            </div>
            <div class="h-200px overflow-auto">
              <Tree
                :tree-data="isActionForm ? formFields : childFlowFields"
                :fieldNames="{ key: 'name' }"
                v-model:selectedKeys="childSelectedKeys"
              />
            </div>
            <div class="text-center cursor-pointer" v-if="!isActionForm" @click="handleSetField(2)">
              子 → 父
            </div>
          </div>
        </div>
      </template>
      <template #p2s>
        <div v-for="(item, index) in parent2child" :key="'p' + index">
          {{ item.parentTitle }} → {{ item.subTitle }}
          <CloseOutlined
            style="color: #f00"
            class="cursor-pointer"
            @click="handleClearItem(1, index)"
          />
        </div>
      </template>
      <template #s2P>
        <div v-for="(item, index) in child2parent" :key="'p' + index">
          {{ item.parentTitle }} → {{ item.subTitle }}
          <CloseOutlined
            style="color: #f00"
            class="cursor-pointer"
            @click="handleClearItem(2, index)"
          />
        </div>
      </template>
    </BasicForm>
    <div class="h-300px flex items-center justify-center" v-if="!isSelected">
      <Empty :image="simpleImage" description="请选择节点" />
    </div>
    <SelectPositionModal
      @register="registerModalSelectPostion"
      @success="handleSuccessSelectPosition"
    />
    <SelectRoleModal @register="registerModalSelectRole" @success="handleSuccessSelectRole" />
    <SelectUser @register="registerModalSelectUser" @success="handleSuccessSelectUser" />
    <SelectFieldWriteTextModal
      @register="registerModalSelectFieldWriteText"
      @success="handleSuccessSelectFieldWriteText"
    />
    <SelActionModal @register="registerModalSelAction" @success="handleSuccessSelAction" />
    <SelFieldModal @register="registerModalSelField" @success="handleSuccessSelField" />
    <ConfigurationModal
      @register="registerModalConfiguration"
      @success="handleSuccessConfiguration"
    />

    <DesignIframe
      @register="registerModalDesignIframe"
      @success="handleSuccessDesignIframe"
      ref="ifrmRef"
    />
    <SelectUser @register="registerSelectAllModal" @success="handleSuccessSelectAllModal" />
  </ScrollContainer>
</template>

<script lang="ts" setup>
  import { ref, watch, unref, onMounted, onUnmounted, nextTick, computed } from 'vue';
  import type { PropType } from 'vue';
  import { BasicForm, useForm, RadioButtonGroup } from '/@/components/Form/index';
  import { ScrollContainer } from '/@/components/Container';
  import {
    formSchema,
    rankList,
    timeDelayedUnitList,
    strategyList,
    colorList,
    actionApplicantSelScopeOptions,
    ActionApplicantSelModeOptions,
  } from './nodeEdit.data';
  import { useI18n } from '/@/hooks/web/useI18n';
  import {
    Checkbox,
    Input,
    Select,
    Divider,
    Empty,
    Tree,
    Form,
    Popover,
    Button,
  } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { SelectUser } from '/@/components/CustomComp/index';
  import SelectPositionModal from './modules/SelectPositionModal.vue';
  import SelectRoleModal from './modules/SelectRoleModal.vue';
  import SelectFieldWriteTextModal from './modules/SelectFieldWriteTextModal.vue';
  import SelActionModal from './modules/SelActionModal.vue';
  import SelFieldModal from './modules/SelFieldModal.vue';
  // import { SelectAll } from '/@/components/CustomComp';

  import {
    CaretUpOutlined,
    CaretDownOutlined,
    CloseOutlined,
    SettingOutlined,
    DownOutlined,
    UserOutlined,
  } from '@ant-design/icons-vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useFlowStore } from '/@/store/modules/flow';
  import {
    getFormGetFields,
    getMyflowGenerateWorkflowString,
    getAdminUpdateWorkflowProps,
  } from '/@/api/flowManage/flowManage';
  import { getFieldsOfDept, getRoleMultilSel } from '/@/api/system/system';

  import { isArray } from '/@/utils/is';
  import {
    getDirTree,
    getFields,
    getFieldsWithNestForNode,
    getFormViews,
    getFormList,
  } from '/@/api/process/process';
  import ConfigurationModal from './modules/configuration/ConfigurationModal.vue';
  import { WorkflowActionDb } from '/@/enums/flowManage';
  import { DesignIframe } from '/@/views/system/workflow/flowManagement/modules/flowPicture/modules/modules/index';
  import { useUserStore } from '/@/store/modules/user';
  import { AceEditor } from '/@/components/AceEditor/index';

  const SelectOption = Select.Option;
  const FormItemRest = Form.ItemRest;
  const InputTextArea = Input.TextArea;
  const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
  const { t } = useI18n();
  const { createMessage } = useMessage();
  const props = defineProps({
    formCode: {
      type: String as PropType<string>,
      default: '',
    },
    typeCode: {
      type: String as PropType<string>,
      default: '',
    },
    isCircleReadEnabled: {
      type: Boolean as PropType<boolean>,
      default: false,
    },
  });
  const emits = defineEmits(['success']);
  const formFields = ref<Recordable[]>([]);

  const loading = ref(false);
  const dataRef: any = ref({});
  const useFlow = useFlowStore();
  const isSelected = ref(false);
  const isScriptEditable = ref(0);
  const isInredEnabled = ref(true);
  const privActionForm = ref('');
  const curActionForm = ref('');

  const roleMultilSelData = ref<any>([]);
  async function getRoleMultilSelData() {
    await getRoleMultilSel().then((res) => {
      const data = res || [];
      roleMultilSelData.value = data.map((item) => {
        return {
          code: item.code,
          name: item.description,
        };
      });
    });
  }
  watch(
    () => useFlow.currentFlowData,
    async () => {
      await nextTick();
      dataRef.value = useFlow.currentFlowData;
      await getDataList();
      getRoleMultilSelData();
      console.log('watch dataRef', dataRef.value);
      // updateSchema({
      //   field: 'actionForm',
      //   show: dataRef.value.inDegree > 0,
      // });
      isSelected.value = false;
      if (dataRef.value && Object.keys(dataRef.value).length) {
        isSelected.value = true;
        fetch();

        let scripts = dataRef.value.nodeScript;
        dataRef.value.nodeScript = '';
        setTimeout(() => {
          dataRef.value.nodeScript = scripts;
        }, 500);
      }
    },
    {
      immediate: true,
    },
  );
  // watchEffect(() => {
  //   dataRef.value = useFlow.currentFlowData;
  //   console.log('dataRef1', dataRef.value);
  //   isSelected.value = false;
  //   if (dataRef.value && Object.keys(dataRef.value).length) {
  //     isSelected.value = true;
  //     setTimeout(() => {
  //       fetch();
  //     }, 500);
  //   }
  // });
  let formdata = {};
  const customSubmitFunc = async (isSubmit) => {
    try {
      const values = await validate();
      console.log('customSubmitFunc values', values);
      formdata = Object.assign({}, dataRef.value, values);
      console.log('formdata1', formdata);

      if (
        formdata['ActionApplicantAssignedRoles'] &&
        formdata['ActionApplicantAssignedRoles'].length
      ) {
        formdata['ActionApplicantAssignedRoles'] = roleMultilSelData.value.filter((item) =>
          formdata['ActionApplicantAssignedRoles'].includes(item.code),
        );
      }

      for (let v in formdata) {
        if (formdata[v] == null || formdata[v] == undefined) {
          formdata[v] == '';
        }
      }
      let flag = '';
      // if (!window.parent.isActionSelected()) {
      //   jAlert('请选择节点且只能选择一个！', '提示');
      //   return;
      // }

      // if (isSubmit && o('title').value == '') {
      //   jAlert('请填写标题！', '提示');
      //   o('title').focus();
      //   return;
      // }
      if (isSubmit && formdata['kind'] == WorkflowActionDb.KIND_READ) {
        if (formdata['fieldWriteText']) {
          createMessage.warning('审阅时只能查看，不能填写可写字段！');
          return;
        }
      }

      console.log('strategyList', strategyList);

      if (formdata['flagModify']) flag = '1';
      else flag = '0';
      if (formdata['flagSel']) flag += '1';
      else flag += '0';
      if (formdata['flagDiscardFlow']) flag += '1';
      else flag += '0';
      if (formdata['flagDelFlow']) flag += '1';
      else flag += '0';
      flag += formdata['flagSaveArchive'];
      if (formdata['flagDelAttach']) flag += '1';
      else flag += '0';
      if (formdata['flagXorRadiate']) flag += '1';
      else flag += '0';
      if (formdata['flagXorAggregate']) flag += '1';
      else flag += '0';
      if (formdata['flagFinishFlow']) flag += '1';
      else flag += '0';
      if (formdata['flagEditAttach']) flag += '1';
      else flag += '0';
      if (formdata['flagReceiveRevise']) flag += '1';
      else flag += '0';
      if (formdata['flagAgreeAndFinish']) {
        flag += '1';
      } else {
        flag += '0';
      }
      if (formdata['flagXorFinish']) {
        flag += '1';
      } else {
        flag += '0';
      }
      if (formdata['flagXorReturn']) {
        flag += '1';
      } else {
        flag += '0';
      }
      if (formdata['flagSeal']) {
        flag += '1';
      } else {
        flag += '0';
      }
      if (formdata['flagTransfer']) {
        flag += '1';
      } else {
        flag += '0';
      }
      if (formdata['flagReaded']) {
        flag += '1';
      } else {
        flag += '0';
      }
      if (formdata['flagCircleRead']) {
        flag += '1';
      } else {
        flag += '0';
      }
      if (formdata['flagForceRecall']) {
        flag += '1';
      } else {
        flag += '0';
      }
      if (formdata['flagAppendUser']) {
        flag += '1';
      } else {
        flag += '0';
      }
      if (formdata['flagWatermark']) {
        flag += '1';
        updateSchema({
          field: 'watermarkText',
          ifShow: true,
        });
      } else {
        flag += '0';
        updateSchema({
          field: 'watermarkText',
          ifShow: false,
        });
      }

      console.log('flag', flag);
      let rankName = '';
      if (formdata['rank']) {
        const rankModel: any = rankList.find((item) => item.value === formdata['rank']);
        rankName = rankModel?.label;
      }
      let rel = '0';
      if (formdata['relateRoleToOrganization']) rel = '1';

      let isMsg = '0';
      if (formdata['isMsg']) {
        isMsg = '1';
      }

      // 检查fieldWrite与fieldHide不能有重叠
      if (
        formdata['fieldHide'] &&
        formdata['fieldHide'].trim() != '' &&
        formdata['fieldWrite'] &&
        formdata['fieldWrite'].trim() != ''
      ) {
        let hides = formdata['fieldHide'] ? formdata['fieldHide'].trim().split(',') : '';
        let hidesText = formdata['fieldHideText']
          ? formdata['fieldHideText'].trim().split(',')
          : '';
        let writes = formdata['fieldWrite'] ? formdata['fieldWrite'].trim().split(',') : '';
        let writesText = formdata['fieldWriteText']
          ? formdata['fieldWriteText'].trim().split(',')
          : '';
        for (let i = 0; i < hides.length; i++) {
          for (let j = 0; j < writes.length; j++) {
            if (hides[i] == writes[j]) {
              if (hidesText[i]) {
                createMessage.warning(
                  '出现相同字段：' + hidesText[i] + '，注意可填写字段与隐藏字段不能有重叠！',
                );
              } else {
                createMessage.warning(
                  '出现相同字段：' + hides[i] + '，注意可填写字段与隐藏字段不能有重叠！',
                );
              }
              return;
            }
          }
        }
      }

      let stra = formdata['strategy'];
      if (stra == null) {
        stra = '';
      }
      if (stra.indexOf('x') != -1) {
        formdata['strategy'] = `x_${formdata['x_num']}`;
      }
      // if (stra.indexOf('x') == 0) {
      //   if ($('#x_span').is(':hidden')) {
      //     $('#x_span').show();
      //   } else {
      //     let xnum = $('#x_num').val();
      //     let type = /^[0-9]*[1-9][0-9]*$/;
      //     let re = new RegExp(type);
      //     if (xnum.match(re) == null) {
      //       createMessage.warning('x必须为正整数！')
      //       return;
      //     }
      //     let xtext = $("#strategy option[value='" + stra + "']").text();
      //     $("#strategy option[value='" + stra + "']").remove();
      //     $('#strategy').append("<option value='x_" + xnum + "'>" + xtext + '</option>');
      //     $("#strategy option[value='x_" + xnum + "']").attr('selected', true);
      //   }
      // } else {
      //   if (!$('#x_span').is(':hidden')) {
      //     let xnum = $('#x_num').val();
      //     let xtext = $("#strategy option[value='x_" + xnum + "']").text();
      //     $("#strategy option[value='x_" + xnum + "']").remove();
      //     $('#strategy').append("<option value='x'>" + xtext + '</option>');
      //     $('#x_num').val('');
      //     $('#x_span').hide();
      //   }
      // }

      let isDelayed = formdata['isDelayed'] ? '1' : '0';
      let timeDelayedValue = formdata['timeDelayedValue'] || '';
      let timeDelayedUnit = formdata['timeDelayedUnit'] || '';
      let canPrivUserModifyDelayDate = formdata['canPrivUserModifyDelayDate'] ? '1' : '0';

      let item2 =
        '{' +
        (formdata['relateToAction'] ? formdata['relateToAction'] : '') +
        ',' +
        formdata['ignoreType'] +
        ',' +
        formdata['kind'] +
        ',' +
        (formdata['fieldHide'] ? formdata['fieldHide'].replaceAll(',', '|') : '') +
        ',' +
        isDelayed +
        ',' +
        timeDelayedValue +
        ',' +
        timeDelayedUnit +
        ',' +
        canPrivUserModifyDelayDate +
        ',' +
        formdata['formView'] +
        ',' +
        (formdata['relateDeptManager'] ? 1 : 0) +
        '}';

      console.log('customSubmitFunc item2', item2);

      makeSubFlowProp();
      console.log({
        kind: formdata['kind'],
        parent2child: parent2child.value,
        child2parent: child2parent.value,
        item2: item2,
      });
      if (isSubmit && formdata['kind'] == '2') {
        // $('#p2s').html() == '' || $('#s2p').html() == ''
        // if (parent2child.value.length === 0 || child2parent.value.length === 0) {
        if (parent2child.value.length === 0) {
          createMessage.warning('请设置父子字段映射！');
          return false;
        }
      }

      console.log('formdata', formdata);
      console.log("formdata['msgProps']", formdata['msgProps']);
      // useFlow.setFlowEdit({ ...useFlow.flowEdit, msgProps: formdata['msgProps'] });
      if (isSubmit) {
        ModifyAction(
          '',
          formdata['title'],
          formdata['OfficeColorIndex'],
          '',
          formdata['userName'],
          formdata['userRealName'],
          formdata['direction'],
          formdata['rank'],
          rankName,
          rel,
          formdata['fieldWrite'],
          formdata['checkState'],
          isArray(formdata['dept']) && formdata['dept'].length ? formdata['dept'].join(',') : '',
          flag,
          formdata['nodeMode'],
          formdata['strategy'],
          formdata['item1'],
          item2,
          isMsg,
          formdata['watermarkText'],
          formdata['actionForm'],
          formdata['actionFormMode'],

          formdata['ActionApproverType'],
          formdata['ActionApplicantSelMode'],
          formdata['ActionApplicantSelScope'],
          formdata['ActionApplicantAssignedUsers'],
          formdata['ActionApplicantAssignedRoles'],
        );
      } else {
        ModifyActionNotSubmit(
          '',
          formdata['title'],
          formdata['OfficeColorIndex'],
          '',
          formdata['userName'],
          formdata['userRealName'],
          formdata['direction'],
          formdata['rank'],
          rankName,
          rel,
          formdata['fieldWrite'],
          formdata['checkState'],
          isArray(formdata['dept']) && formdata['dept'].length ? formdata['dept'].join(',') : '',
          flag,
          formdata['nodeMode'],
          formdata['strategy'],
          formdata['item1'],
          item2,
          isMsg,
          formdata['watermarkText'],
          formdata['actionForm'],
          formdata['actionFormMode'],
          formdata['ActionApproverType'],
          formdata['ActionApplicantSelMode'],
          formdata['ActionApplicantSelScope'],
          formdata['ActionApplicantAssignedUsers'],
          formdata['ActionApplicantAssignedRoles'],
        );
      }

      // if (userRealName.value == '脚本') o('nodeScriptTr').style.display = '';
      // else o('nodeScriptTr').style.display = 'none';

      // window.close();
      // emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    } catch (err) {
      console.log('customSubmitFunc', err);
    } finally {
    }
  };
  const ModifyAction = (
    user,
    title,
    clrindex,
    userRealName,
    jobCode,
    jobName,
    proxyJobCode,
    proxyJobName,
    proxyUserName,
    proxyUserRealName,
    fieldWrite,
    checkState,
    dept,
    flag,
    nodeMode,
    strategy,
    isEndNode,
    item2,
    isMsg,
    watermarkText,
    actionForm,
    actionFormMode,
    ActionApproverType,
    ActionApplicantSelMode,
    ActionApplicantSelScope,
    ActionApplicantAssignedUsers,
    ActionApplicantAssignedRoles,
  ) => {
    let result = ModifyActionNotSubmit(
      user,
      title,
      clrindex,
      userRealName,
      jobCode,
      jobName,
      proxyJobCode,
      proxyJobName,
      proxyUserName,
      proxyUserRealName,
      fieldWrite,
      checkState,
      dept,
      flag,
      nodeMode,
      strategy,
      isEndNode,
      item2,
      isMsg,
      watermarkText,
      actionForm,
      actionFormMode,
      ActionApproverType,
      ActionApplicantSelMode,
      ActionApplicantSelScope,
      ActionApplicantAssignedUsers,
      ActionApplicantAssignedRoles,
    );

    if (result == 1) submitDesigner();
  };
  let curInternalName = '';
  const ModifyActionNotSubmit = (
    user,
    title,
    clrindex,
    userRealName,
    jobCode,
    jobName,
    proxyJobCode,
    proxyJobName,
    proxyUserName,
    proxyUserRealName,
    fieldWrite,
    checkState,
    dept,
    flag,
    nodeMode,
    strategy,
    isEndNode,
    item2,
    isMsg,
    watermarkText,
    actionForm,
    actionFormMode,
    ActionApproverType,
    ActionApplicantSelMode,
    ActionApplicantSelScope,
    ActionApplicantAssignedUsers,
    ActionApplicantAssignedRoles,
  ) => {
    console.log({
      user,
      title,
      clrindex,
      userRealName,
      jobCode,
      jobName,
      proxyJobCode,
      proxyJobName,
      proxyUserName,
      proxyUserRealName,
      fieldWrite,
      checkState,
      dept,
      flag,
      nodeMode,
      strategy,
      isEndNode,
      item2,
      isMsg,
      watermarkText,
      actionForm,
      ActionApproverType,
      ActionApplicantSelMode,
      ActionApplicantSelScope,
      ActionApplicantAssignedUsers,
      ActionApplicantAssignedRoles,
    });
    // let myflow = $.myflow;
    const { curAction: _r } = useFlow.getFlowInfo;
    console.log('_r', _r, 'id', _r.getId());
    if (_r == null) {
      return -1;
    }

    let myflow = $.myflow;
    console.log('myflow.getStates()', myflow.getStates());
    let _rect = myflow.getStates()[_r.getId()];
    console.log('_rect', _rect);
    if (_rect == null) {
      createMessage.warn('节点已被删除');
      return -1;
    }

    // 清除属性
    _r.clearProps();

    _r.setText(jobName + '：' + title);
    _r.setProp('ActionUser', user);
    _r.setProp('ActionTitle', title);

    _r.setProp('ActionUserRealName', userRealName);
    _r.setProp('ActionJobCode', jobCode);
    _r.setProp('ActionJobName', jobName);
    _r.setProp('ActionProxyJobCode', proxyJobCode);
    _r.setProp('ActionProxyJobName', proxyJobName);
    _r.setProp('ActionProxyUserName', proxyUserName);
    _r.setProp('ActionProxyUserRealName', proxyUserRealName);
    _r.setProp('ActionColorIndex', clrindex);
    _r.setProp('ActionFieldWrite', fieldWrite);
    _r.setProp('ActionCheckState', checkState);

    _r.setProp('ActionDept', dept);
    _r.setProp('ActionFlag', flag);
    _r.setProp('ActionDeptMode', Number(nodeMode));
    _r.setProp('ActionStrategy', strategy);
    _r.setProp('ActionItem1', isEndNode);
    _r.setProp('ActionItem2', String(item2));
    _r.setProp('ActionIsMsg', isMsg);

    _r.setProp('ActionWatermarkText', watermarkText);
    _r.setProp('ActionForm', actionForm);
    _r.setProp('ActionFormMode', actionFormMode);

    _r.setProp('ActionApproverType', ActionApproverType);
    _r.setProp('ActionApplicantSelMode', ActionApplicantSelMode);
    _r.setProp('ActionApplicantSelScope', ActionApplicantSelScope);
    _r.setProp(
      'ActionApplicantAssignedUsers',
      isArray(ActionApplicantAssignedUsers)
        ? encodeStr(JSON.stringify(ActionApplicantAssignedUsers))
        : '',
    );
    _r.setProp(
      'ActionApplicantAssignedRoles',
      isArray(ActionApplicantAssignedRoles)
        ? encodeStr(JSON.stringify(ActionApplicantAssignedRoles))
        : '',
    );

    // 使_name能够刷新，因为_name中显示的为_text的经过省略号处理的文本
    _r.resize();

    // console.log(_r.toJson());
    if (isEndNode == 1) {
      _r.setType('end');
    } else {
      // 如果原来是结束节点，则变为任务节点
      // 注意不能直接置为task，因为有可能为开始节点
      if (_r.getType() == 'end') {
        _r.setType('task');
      }
    }

    return 1;
  };

  function encodeStr(str) {
    console.log('str', str);
    if (!str) return '';
    if (!str.trim()) return '';
    str = str.replaceAll('\\[', '#@#lbracket');
    str = str.replaceAll('\\]', '#@#rbracket');
    str = str.replaceAll(';', '#@#fenghao');
    str = str.replaceAll(':', '#@#maohao');
    str = str.replaceAll(',', '#@#douhao');
    str = str.replaceAll('\r\n', '#@#huanhang');
    str = str.replaceAll('\n', '#@#huanhang'); // textarea中的换行是\n
    str = str.replaceAll('"', '#@#shuangyinhao');
    str = str.replaceAll("'", '#@#danyinhao'); // 不能用singlequot，因为quot会先被替换掉
    console.log('encodeStr', str);
    return str;
  }

  const submitDesigner = async () => {
    if (formdata['title'] == '') {
      createMessage.warning('请填写标题');
      return;
    }
    let myflow = $.myflow;
    console.log('myflow', myflow);
    let flowJson = myflow.getJson();
    let flowString = ''; //myflow.getWorkflow();
    const serverName = window.location.hostname;
    const flowStringRecord = await getMyflowGenerateWorkflowString({
      flowJson: flowJson,
      serverName: serverName,
    });
    flowString = flowStringRecord.flowString;
    console.log('flowJson', flowJson);
    console.log('flowString', flowString);
    // console.log("myflow.getWorkflow()=" + flowString);
    // let op = o('op').value;
    let op = formdata['op'];
    // let url = op == 'edit' ? 'modifyFlowPredefined' : 'createFlowPredefined';
    console.log('useflow', useFlow);
    console.log('formdata', formdata);
    const flowEdit = useFlow.flowEdit;
    console.log('flowEdit', flowEdit);
    const form = {
      op: flowEdit['op'],
      title: flowEdit['title'],
      dirCode: flowEdit['dirCode'],
      examine: flowEdit['examine'],
      id: flowEdit['id'],
      flowString: flowString,
      flowJson: flowJson,
      typeCode: flowEdit['typeCode'],
      returnBack: flowEdit['returnBack'],
      isReactive: flowEdit['isReactive'] ? '1' : '0',
      isRecall: flowEdit['isRecall'] ? '1' : '0',
      returnMode: flowEdit['returnMode'],
      returnStyle: flowEdit['returnStyle'],
      roleRankMode: flowEdit['roleRankMode'],
      props: flowEdit['props'],
      views: flowEdit['views'],
      isDistribute: flowEdit['isDistribute'] ? '1' : '0',
      toghterCondition: flowEdit['hiddenCondition'],
      msgProp: flowEdit['msgProps'],
      isPlus: flowEdit['isPlus'] ? '1' : '0',
      isTransfer: flowEdit['isTransfer'] ? '1' : '0',
      isReply: flowEdit['isReply'] ? '1' : '0',
      isModuleFilter: flowEdit['isModuleFilter'] ? '1' : '0',
      downloadCount: flowEdit['downloadCount'],
      canDelOnReturn: flowEdit['canDelOnReturn'] ? '1' : '0',
      startMode: !flowEdit['startMode'] ? '1' : flowEdit['startMode'],
      rules: isArray(flowEdit['rules']) ? JSON.stringify(flowEdit['rules']) : flowEdit['rules'],
    };
    console.log('form', form);
    const res = await getAdminUpdateWorkflowProps(form);
    emits('success');
    // emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
    createMessage.success('操作成功');
    // fetch();
    //   data: {
    //     op: o('op').value,
    //     title: o('title').value,
    //     dirCode: o('dirCode').value,
    //     examine: o('examine').value,
    //     id: o('id').value,
    //     flowString: flowString,
    //     flowJson: flowJson,
    //     typeCode: o('typeCode').value,
    //     returnBack: o('returnBack').value,
    //     isReactive: o('isReactive').checked ? o('isReactive').value : '0',
    //     isRecall: o('isRecall').checked ? o('isRecall').value : '0',
    //     returnMode: o('returnMode').value,
    //     returnStyle: o('returnStyle').value,
    //     roleRankMode: o('roleRankMode').value,
    //     props: o('props').value,
    //     views: o('views').value,
    //     isDistribute: o('isDistribute').checked ? o('isDistribute').value : '0',
    //     toghterCondition: o('hiddenCondition').value,
    //     msgProp: o('hiddenMsgProp').value,
    //     isPlus: o('isPlus').checked ? o('isPlus').value : '0',
    //     isTransfer: o('isTransfer').checked ? o('isTransfer').value : '0',
    //     isReply: o('isReply').checked ? o('isReply').value : '0',
    //     isModuleFilter: o('isModuleFilter').checked ? '1' : '0',
    //     downloadCount: o('downloadCount').value,
    //     canDelOnReturn: o('canDelOnReturn').checked ? '1' : '0',
    //   },
  };
  const [registerForm, { setFieldsValue, updateSchema, resetFields, validate, getFieldsValue }] =
    useForm({
      labelWidth: 80,
      schemas: formSchema,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 23,
      },
      labelWrap: true,
      submitFunc: void customSubmitFunc,
    });

  const fetch = async () => {
    try {
      resetFields();

      let myflow = $.myflow;
      let paths = myflow.getPaths();
      console.log('paths', paths);
      let states = myflow.getStates();
      privActionForm.value = '';
      for (let key in paths) {
        // 确保key是对象自身的属性
        if (paths.hasOwnProperty(key)) {
          // console.log('fetch paths[key] to', paths[key].to().getId());
          // 删除连线操作后会出现为null的path，保存后就没有了，所以此处如果不判断，会导致属性中出现大量的undefind，因为运行到这里报错，节点上的属性未能被赋值，再保存以后就会出现 undefined
          if (paths[key] && paths[key].to().getId() == dataRef.value.internalName) {
            // 找到上一节点中设置的表单
            for (let k in states) {
              // 删除节点后也会出现为null的state
              if (states[k] && states[k].getId() == paths[key].from().getId()) {
                privActionForm.value = states[k].getPropVal('ActionForm');
                break;
              }
            }
          }
        }
      }

      if (privActionForm.value == '') {
        privActionForm.value = props.formCode;
      }

      console.log(dataRef.value.actionForm + '--' + privActionForm.value);
      console.log('dataRef.value.inDegree', dataRef.value.inDegree);
      if (dataRef.value.inDegree != 0) {
        let curNodeForm = dataRef.value.actionForm;
        if (curNodeForm == '') {
          curNodeForm = props.formCode;
        }
        curActionForm.value = curNodeForm;

        if (curNodeForm != privActionForm.value) {
          getFieldsByPrivActionForm(privActionForm.value);

          updateSchema([
            { field: 'trMapField', ifShow: true },
            {
              field: 'p2s',
              label: '  ', // 映射内容
              ifShow: true,
            },
            {
              field: 's2P',
              ifShow: false,
            },
          ]);

          console.log('fetch parentToSubMap', dataRef.value.parentToSubMap);
          parent2child.value = [];
          if (isArray(dataRef.value.parentToSubMap)) {
            parent2child.value = dataRef.value.parentToSubMap;
          }
        }
      } else {
        updateSchema([
          { field: 'trMapField', ifShow: false },
          {
            field: 'p2s',
            label: '  ', // 映射内容
            ifShow: false,
          },
        ]);
      }

      if (isArray(mockData.value)) {
        if (dataRef.value.fieldWrite) {
          const fieldWrites = dataRef.value.fieldWrite.split(',');
          console.log('fieldWrites', fieldWrites);
          console.log('mockData', mockData.value);
          dataRef.value.fieldWriteText = mockData.value
            .filter((item: any) => fieldWrites.includes(item.name))
            .map((item: any) => item.title)
            .join(',');
        } else {
          dataRef.value.fieldWriteText = '';
        }
        if (dataRef.value.fieldHide) {
          const fieldHides = dataRef.value.fieldHide.split(',');
          dataRef.value.fieldHideText = mockData.value
            .filter((item: any) => fieldHides.includes(item.name))
            .map((item: any) => item.title)
            .join(',');
        } else {
          dataRef.value.fieldHideText = '';
        }
      }

      if (dataRef.value.kind == '2') {
        parent2child.value = [];
        if (isArray(dataRef.value.parentToSubMap)) {
          parent2child.value = dataRef.value.parentToSubMap;
        }
        child2parent.value = [];
        if (isArray(dataRef.value.subToParentMap)) {
          child2parent.value = dataRef.value.subToParentMap;
        }
        getChildFlowFields();
      }

      getFieldsOfDeptData();

      console.log('mockData.value', mockData.value);
      console.log('dataRef.value.fieldWriteText', dataRef.value.fieldWriteText);
      console.log('dataRef.value1', dataRef.value);
      console.log('nodeScript', dataRef.value.nodeScript);
      console.log('deptField', dataRef.value.deptField);
      if (dataRef.value.deptField == 'undefined') dataRef.value.deptField = [];
      else if (dataRef.value.deptField) {
        dataRef.value.deptField = dataRef.value.deptField.split(',');
      }
      setFieldsValue({ ...dataRef.value });

      if (dataRef.value['flagWatermark']) {
        updateSchema({
          field: 'watermarkText',
          ifShow: true,
        });
      } else {
        updateSchema({
          field: 'watermarkText',
          ifShow: false,
        });
      }

      updateSchema([
        {
          field: 'direction',
          componentProps: {
            onChange: () => {
              customSubmitFunc(false);
            },
          },
        },
        {
          field: 'title',
          componentProps: {
            onChange: () => {
              customSubmitFunc(false);
            },
          },
        },
        {
          field: 'item1',
          componentProps: {
            onChange: () => {
              customSubmitFunc(false);
            },
          },
        },
      ]);

      if (!dataRef.value.inDegree) {
        updateSchema({
          field: 'relateRoleToOrganization',
          ifShow: false,
        });
      } else {
        updateSchema({
          field: 'relateRoleToOrganization',
          // ifShow: true,
          ifShow: dataRef.value.ActionApproverType == '0' || !dataRef.value.ActionApproverType,
        });
      }

      getFieldsByForm(dataRef.value.actionForm || props.formCode);
    } catch (err) {
      console.error('fetch', err);
    }
  };

  const handleResetFields = () => {
    resetFields();
  };

  //取得表单中部门型的字段，以限定部门
  const fieldsOfDept = ref([]);
  const getFieldsOfDeptData = async () => {
    try {
      const res = await getFieldsOfDept({ formCode: props.formCode });
      fieldsOfDept.value = res || [];
      fieldsOfDept.value.forEach((item: any) => {
        delete item.options;
      });
      updateSchema([
        {
          field: 'deptField',
          componentProps: {
            options: fieldsOfDept.value,
            fieldNames: { label: 'title', value: 'name' },
          },
        },
      ]);
    } catch (err) {
      console.log('getFieldsOfDeptData', err);
    }
  };
  const mockData = ref<any[]>([]);
  const getDataList = async () => {
    // let params = {
    //   formCode: props.formCode,
    // };
    // await getFormGetFields(params).then((res) => {
    //   let data = res || [];
    //   data.forEach((item) => {
    //     item.key = item.name;
    //     item.description = item.title;
    //   });
    //   mockData.value = data;
    // });
    if (!props.formCode) return;
    let params = {
      formCode: dataRef.value.actionForm || props.formCode,
    };
    await getFieldsWithNestForNode(params).then((res) => {
      let data = res || [];
      data.forEach((item) => {
        item.key = item.name;
        item.description = item.title;
      });
      mockData.value = data;
    });
  };
  // watch(
  //   () => props.formCode,
  //   (newVal) => {
  //     console.log('newVal', newVal);
  //     if (newVal) {
  //       getDataList();
  //     }
  //   },
  //   {
  //     immediate: true,
  //   },
  // );

  //自己
  const handleSelf = () => {
    console.log('本人');
    dataRef.value.userName = '$self';
    setSpanMode('用户', '本人');
  };

  const [registerModalSelectRole, { openModal: openSelectRole }] = useModal();
  //选择角色
  const handleSelectRole = () => {
    console.log('选择角色');
    let targetKeys = [];
    if (dataRef.value.nodeMode == 0) {
      targetKeys = dataRef.value?.userName ? dataRef.value.userName.split(',') : [];
    }
    openSelectRole(true, {
      record: {
        targetKeys,
      },
    });
  };
  //选择角色回调
  const handleSuccessSelectRole = ({ codes, codeTexts }) => {
    console.log('选择角色回调', { codes, codeTexts });
    dataRef.value.userName = codes;
    dataRef.value.userRealName = codeTexts;
    const record = getFieldsValue();
    console.log('record', record);
    dataRef.value.relateRoleToOrganization = record.relateRoleToOrganization;
    if (record.relateRoleToOrganization) {
      if (codes.indexOf(',') != -1) {
        dataRef.value.relateRoleToOrganization = false;
        createMessage.warning('多个角色被选择，角色关联已经被取消！');
      }
    }
    setFieldsValue({
      relateRoleToOrganization: dataRef.value.relateRoleToOrganization,
    });
    setSpanMode('角色', dataRef.value.userRealName, '0');
  };

  const [registerModalSelectPostion, { openModal: openSelectPosition }] = useModal();
  //选择岗位
  const handleSelectPosition = () => {
    console.log('选择岗位', dataRef.value);
    let targetKeys: String[] = [];
    if (dataRef.value.nodeMode == 4 && dataRef.value.userName) {
      targetKeys = dataRef.value.userName.split(',').map((item) => item - 0);
    }
    openSelectPosition(true, {
      targetKeys,
    });
  };

  //选择岗位回调
  const handleSuccessSelectPosition = ({ value, label }) => {
    console.log('岗位回调');
    dataRef.value.userName = value;
    dataRef.value.userRealName = label;
    setSpanMode('岗位', dataRef.value.userRealName, '4');
  };

  const [registerModalSelectUser, { openModal: openSelectUser }] = useModal();
  //选择用户
  const handleSelectUser = () => {
    let users: Recordable[] = [];
    if (
      dataRef.value.nodeMode == 1 &&
      dataRef.value.userName != '$self' &&
      dataRef.value.userName != '$starter' &&
      dataRef.value.userName != '$userSelect' &&
      dataRef.value.userName != '$myleader' &&
      dataRef.value.userName != '$mysubordinate' &&
      dataRef.value.userName &&
      dataRef.value.userRealName
    ) {
      const userNames: String[] = dataRef.value.userName.split(',');
      const userRealNames: String[] = dataRef.value.userRealName.split(',');
      userNames.forEach((item, index) => {
        users.push({
          name: item,
          key: item,
          realName: userRealNames[index],
          title: userRealNames[index],
        });
      });
    }
    console.log('选择用户', users);
    openSelectUser(true, {
      users,
    });
  };
  //选择用户回调
  const handleSuccessSelectUser = (users: Recordable[]) => {
    console.log('选择用户回调', users);
    if (users && users.length) {
      let userNames: String[] = [];
      let keys: String[] = [];

      users.forEach((item) => {
        userNames.push(item.title);
        keys.push(item.key);
      });
      dataRef.value.userRealName = userNames.join(',');
      dataRef.value.userName = keys.join(',');
    }
    setSpanMode('用户', dataRef.value.userRealName);
  };

  //发起人
  const handleSendPerson = () => {
    dataRef.value.userName = '$starter';
    setSpanMode('发起人', '发起人');
  };
  //自选用户
  const handleSelfSelectUser = () => {
    dataRef.value.userName = '$userSelect';
    setSpanMode('自选用户', '自选用户');
  };
  const handleMyDept = () => {
    dataRef.value.userName = '$myDept';
    setSpanMode('我的部门', '我的部门');
  };
  //我的领导
  const handleMyleader = () => {
    dataRef.value.userName = '$myleader';
    setSpanMode('我的领导', '我的领导');
  };
  //我的下属
  const handleMysubordinate = () => {
    dataRef.value.userName = '$mysubordinate';
    setSpanMode('我的下属', '我的下属');
  };
  //自选用户管理
  const handleSelfUser = () => {
    dataRef.value.userName = '$userSelectInAdminDept';
    setSpanMode('自选用户(管理)', '自选用户(管理)');
  };

  //部门管理员
  const handleSelectDepart = () => {
    dataRef.value.userName = '$deptManager';
    setSpanMode('部门管理员', '部门管理员');
  };

  const handleAuto = () => {
    dataRef.value.userName = '$auto';
    setSpanMode('自动节点', '自动节点');
  };

  const [registerModalSelAction, { openModal: openSelAction }] = useModal();
  //所选节点上人员
  const selAction = () => {
    // openWin('flow_designer_action_sel.jsp', 800, 300);
    const { curAction } = useFlow.getFlowInfo;
    const curActionId = curAction.getId();
    console.log('curAction', curAction.getId());
    let myflow = $.myflow;
    let _r = myflow.getStates();
    console.log('_r', { _r, myflow });
    let options: Recordable[] = [];
    if (_r && Object.keys(_r).length) {
      for (let v in _r) {
        if (v != curActionId) {
          options.push({
            value: v,
            label: _r[v].text(),
          });
        }
      }
    }
    console.log('options', options);
    openSelAction(true, {
      options,
      userRealName: dataRef.value.userRealName,
    });
  };
  //所选节点回调
  const handleSuccessSelAction = ({ value, label }) => {
    console.log('节点回调');
    dataRef.value.userName = '$action_' + value;
    dataRef.value.userRealName = label;
    setSpanMode(label, dataRef.value.userRealName, '1');
  };
  const [registerModalSelField, { openModal: openSelField }] = useModal();
  //表单中指定人员
  const selField = () => {
    openSelField(true, {
      options: mockData.value,
      formCode: props.formCode,
      userRealName: dataRef.value.userRealName,
    });
  };
  //表单中指定人员回调
  const handleSuccessSelField = ({ value, label }) => {
    console.log('表单中指定人员');
    dataRef.value.userName = '$field_' + value;
    dataRef.value.userRealName = label;
    setSpanMode(label, dataRef.value.userRealName, '1');
  };
  //通过脚本选人
  const showNodeScript = () => {
    dataRef.value.userRealName = '脚本';
    dataRef.value.userName = WorkflowActionDb.PRE_TYPE_NODE_SCRIPT;
    setSpanMode(dataRef.value.userRealName, dataRef.value.userRealName);
  };

  const setSpanMode = (spanMode, userRealName, nodeMode = '1') => {
    dataRef.value.spanMode = spanMode;
    dataRef.value.nodeMode = nodeMode;
    dataRef.value.userRealName = userRealName;
    setFieldsValue({
      spanMode: dataRef.value.spanMode,
      userRealName,
      userName: dataRef.value.userName,
    });
    customSubmitFunc(false);
  };

  const [registerModalSelectFieldWriteText, { openModal: openSelectFieldWriteText }] = useModal();
  //可写字段打开
  const handleSelectFieldWriteText = (type) => {
    let fields: String[] = [];
    if (type == 1 && dataRef.value.fieldWrite) {
      fields = dataRef.value.fieldWrite.split(',');
    } else if (type == 2 && dataRef.value.fieldHide) {
      fields = dataRef.value.fieldHide.split(',');
    }
    openSelectFieldWriteText(true, {
      type: type, //1是可写字段，2是隐藏字段
      record: {
        formCode: dataRef.value.actionForm || props.formCode,
        fields: fields,
        mockData: mockData.value,
      },
    });
  };
  //可写字段回调
  const handleSuccessSelectFieldWriteText = ({ fields, fieldTexts, type = 1 }) => {
    console.log('record回调', { fields, fieldTexts, type });
    if (type == 1) {
      dataRef.value.fieldWrite = fields;
      dataRef.value.fieldWriteText = fieldTexts;
      setFieldsValue({ fieldWriteText: dataRef.value.fieldWriteText });
    } else {
      dataRef.value.fieldHide = fields;
      dataRef.value.fieldHideText = fieldTexts;
      setFieldsValue({ fieldHideText: dataRef.value.fieldHideText });
    }
    customSubmitFunc(false);
  };
  //可写字段清空
  const handleSuccessSelectFieldWriteTextClear = (type) => {
    if (type == 1) {
      dataRef.value.fieldWrite = '';
      dataRef.value.fieldWriteText = '';
      setFieldsValue({ fieldWriteText: dataRef.value.fieldWriteText });
    } else {
      dataRef.value.fieldHide = '';
      dataRef.value.fieldHideText = '';
      setFieldsValue({ fieldHideText: dataRef.value.fieldHideText });
    }
    customSubmitFunc(false);
  };

  const isMoreBut = ref(false);

  //更多处理人员
  const handleMoreBut = () => {
    isMoreBut.value = !isMoreBut.value;
  };

  //子流程
  const childFlowList = ref<Recordable[]>([]);
  //获取子流程
  const getChildFlowList = () => {
    childFlowList.value = [];
    getDirTree().then((res) => {
      let data = res;
      if (data && data.length > 0 && data[0].children && data[0].children.length > 0) {
        let dataSource = data[0].children;
        if (isArray(dataSource)) {
          dataSource.forEach((item: any) => {
            if (item['children'] && item['children'].length > 0)
              item['children'] = item['children'].map((el) => {
                childFlowList.value.push(el);
                return { ...el, loading: false };
              });
          });
        }
      }
    });
  };

  //子流程change
  const getSubFlowTypeCode = (val) => {
    dataRef.value.subFlowTypeCode = val;
    getChildFlowFields();
  };

  const childFlowFields = ref<any[]>([]);
  //获取子流程字段
  const getChildFlowFields = () => {
    childFlowFields.value = [];
    if (!dataRef.value.subFlowTypeCode) return;
    let params = {
      typeCode: dataRef.value.subFlowTypeCode,
    };
    getFields(params).then((res) => {
      let data = res || [];
      childFlowFields.value = data;
    });
  };
  const filterOption = (input: string, option: any) => {
    return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };

  const formDataOptions: any = ref([]);
  const getFormData = () => {
    formDataOptions.value = [];
    getFormList().then((res) => {
      formDataOptions.value = res || [];
      if (isArray(formDataOptions.value) && formDataOptions.value.length) {
        formDataOptions.value.forEach((item: any) => {
          item['label'] = item.name;
          item['value'] = item.code;
        });
        formDataOptions.value.unshift({ value: '', label: '默认' });
        updateSchema({
          field: 'actionForm',
          componentProps: {
            showSearch: true,
            optionFilterProp: 'label',
            options: formDataOptions.value,
            onChange: handleChangeActionForm,
          },
          // show: dataRef.value.inDegree,
        });
      }
    });
  };

  const handleChangeActionForm = (val) => {
    getFormViewsForAction(val);
    getFieldsByForm(val || props.formCode);
    curActionForm.value = val;

    console.log(privActionForm.value + '---' + curActionForm.value);
    let isShow = false;
    if (!curActionForm.value) {
      if (privActionForm.value != props.formCode) {
        isShow = true;
      }
    } else {
      if (privActionForm.value != curActionForm.value) {
        isShow = true;
      }
    }
    if (isShow) {
      getFieldsByPrivActionForm(privActionForm.value);

      updateSchema([
        { field: 'trMapField', ifShow: true },
        {
          field: 'p2s',
          label: '  ', // 映射内容
          ifShow: true,
        },
        {
          field: 's2P',
          ifShow: false,
        },
      ]);
    } else {
      updateSchema([
        { field: 'trMapField', ifShow: false },
        {
          field: 'p2s',
          label: '  ', // 映射内容
          ifShow: false,
        },
      ]);
    }
  };

  const getFieldsByForm = (formCode) => {
    let params = {
      formCode: formCode,
    };
    getFormGetFields(params).then((res) => {
      formFields.value = res || [];
      if (isArray(formFields.value)) {
        formFields.value.forEach((item) => {
          item.value = item.name;
          item.label = item.title;
        });
      }
    });
  };

  const privNextFormFields = ref<any[]>([]);

  // 取上一节点的表单域
  const getFieldsByPrivActionForm = (formCode) => {
    let params = {
      formCode: formCode,
    };
    getFormGetFields(params).then((res) => {
      privNextFormFields.value = res || [];
      if (isArray(formFields.value)) {
        privNextFormFields.value.forEach((item) => {
          item.value = item.name;
          item.label = item.title;
        });
      }
    });
  };

  const getFormViewsForAction = async (formCode = props.formCode) => {
    let result = await getFormViews({ formCode: formCode });
    result.unshift({ id: 0, name: '默认' });
    console.log('getFormViews result', result);
    result.forEach((item) => {
      item.id = '' + item.id;
    });

    updateSchema([
      {
        field: 'formView',
        componentProps: {
          fieldNames: { label: 'name', value: 'id', key: 'id' },
          options: result,
        },
      },
    ]);
  };

  onMounted(async () => {
    getChildFlowList();

    getFormData();

    getFormViewsForAction();

    let params = {
      typeCode: props.typeCode,
    };
    getFields(params).then((res) => {
      formFields.value = res || [];
      if (isArray(formFields.value)) {
        formFields.value.forEach((item) => {
          item.value = item.name;
          item.label = item.title;
        });
      }
    });

    let serverInfo = userStore.getServerInfo;
    isScriptEditable.value = serverInfo.isScriptEditable;
    console.log('isScriptEditable', isScriptEditable.value);
    isInredEnabled.value = serverInfo.isInredEnabled;
  });

  //父流程选中
  const parentSelectedKeys = ref([]);

  //子流程选中
  const childSelectedKeys = ref([]);

  //父到子数据
  const parent2child = ref<Recordable[]>([]);
  //子到父数据
  const child2parent = ref<Recordable[]>([]);

  //点击父 子
  const handleSetField = (type) => {
    console.log({
      parentSelectedKeys: parentSelectedKeys.value,
      childSelectedKeys: childSelectedKeys.value,
    });
    if (parentSelectedKeys.value.length == 0) {
      if (privActionForm.value == '') {
        createMessage.warning('请选择父流程字段');
      } else {
        createMessage.warning('请选择上节点字段');
      }
      return;
    }
    if (childSelectedKeys.value.length == 0) {
      if (privActionForm.value == '') {
        createMessage.warning('请选择子流程字段');
      } else {
        createMessage.warning('请选择本节点字段');
      }
      return;
    }
    let pVal = parentSelectedKeys.value[0];
    let pText;
    if (isActionForm.value) {
      pText = privNextFormFields.value.find(
        (item) => item.name === parentSelectedKeys.value[0],
      )?.title;
    } else {
      pText = mockData.value.find((item) => item.name === parentSelectedKeys.value[0])?.title;
    }
    let sVal = childSelectedKeys.value[0];
    let sText;
    if (isActionForm.value) {
      sText = mockData.value.find((item) => item.name === childSelectedKeys.value[0])?.title;
    } else {
      sText = childFlowFields.value.find((item) => item.name === childSelectedKeys.value[0])?.title;
    }

    if (type == 1) {
      //父到子
      if (isMapExist(type, pVal, sVal)) {
        createMessage.warning('存在重复映射！');
        return;
      }
      makeP2S(pVal, pText, sVal, sText);
    } else if (type == 2) {
      //子到父
      if (isMapExist(type, sVal, pVal)) {
        createMessage.warning('存在重复映射！');
        return;
      }
      makeS2P(pVal, pText, sVal, sText);
    }
  };
  function isMapExist(type, pVal, sVal) {
    if (type == 1) {
      return parent2child.value.some((item) => item.parentField == pVal && item.subField == sVal);
    } else if (type == 2) {
      return child2parent.value.some((item) => item.parentField == pVal && item.subField == sVal);
    }
  }
  function makeP2S(pVal, pText, sVal, sText) {
    parent2child.value.push({
      parentField: pVal,
      subField: sVal,
      parentTitle: pText,
      subTitle: sText,
    });
  }

  function makeS2P(pVal, pText, sVal, sText) {
    child2parent.value.push({
      parentField: sVal,
      subField: pVal,
      parentTitle: sText,
      subTitle: pText,
    });
  }

  function handleClearItem(type, index) {
    if (type == 1) {
      parent2child.value.splice(index, 1);
    } else if (type == 2) {
      child2parent.value.splice(index, 1);
    }
  }

  function xmlEncode(c) {
    return c
      .replaceAll('<', '&lt;')
      .replaceAll('>', '&gt;')
      .replaceAll('&', '&amp;')
      .replaceAll('"', '&quot;');
  }

  function makeSubFlowProp() {
    // {subFlowTypeCode:...,parentToSubMap:{parentField:subField,...},subToParentMap:{subField:parentField}}
    const record = getFieldsValue();
    console.log('makeSubFlowProp getFieldsValue', record);
    let str = '';
    if (record['kind'] == 2 || dataRef.value.privActionForm != '') {
      str = '"subFlowTypeCode":"' + record['subFlowTypeCode'] + '"';
      let parentToSubMap = '';
      parent2child.value.forEach((item) => {
        if (parentToSubMap == '') {
          parentToSubMap =
            '{"parentField":"' +
            item['parentField'] +
            '", "subField":"' +
            item['subField'] +
            '", "parentTitle":"' +
            item['parentTitle']?.trim() +
            '", "subTitle":"' +
            item['subTitle'] +
            '"}';
        } else {
          parentToSubMap +=
            ',{"parentField":"' +
            item['parentField'] +
            '", "subField":"' +
            item['subField'] +
            '", "parentTitle":"' +
            item['parentTitle']?.trim() +
            '", "subTitle":"' +
            item['subTitle'] +
            '"}';
        }
      });

      let subToParentMap = '';
      if (record['kind'] == 2) {
        child2parent.value.forEach((item) => {
          if (subToParentMap == '') {
            subToParentMap =
              '{"parentField":"' +
              item['parentField'] +
              '", "subField":"' +
              item['subField'] +
              '", "parentTitle":"' +
              item['parentTitle']?.trim() +
              '", "subTitle":"' +
              item['subTitle'] +
              '"}';
          } else {
            subToParentMap +=
              ',{"parentField":"' +
              item['parentField'] +
              '", "subField":"' +
              item['subField'] +
              '", "parentTitle":"' +
              item['parentTitle']?.trim() +
              '", "subTitle":"' +
              item['subTitle'] +
              '"}';
          }
        });
      }

      str =
        '{' +
        str +
        ',"parentToSubMap":[' +
        parentToSubMap +
        '], "subToParentMap":[' +
        subToParentMap +
        ']}';
    }

    // 查找internalName对应的项，如果没有，则添加
    let xml = $.parseXML(useFlow.flowEdit?.props); //window.parent.getProps()
    console.log('xml', xml);
    if (!xml) {
      xml = $.parseXML('<actions></actions>');
    }
    let $xml = $(xml);
    $xml
      .find('actions')
      .children()
      .each(function (i) {
        if ($(this).attr('internalName') == useFlow.flowInfo?.curInternalName) {
          // 删除原节点
          $(this).remove();
          return false;
        }
      });

    // 新增节点
    let $elem = $(
      $.parseXML(
        "<action internalName='" +
          useFlow.flowInfo?.curInternalName +
          "'><property>" +
          str +
          '</property>' +
          '<btnAgreeName>' +
          record['btnAgreeName'] +
          '</btnAgreeName>' +
          '<btnRefuseName>' +
          record['btnRefuseName'] +
          '</btnRefuseName>' +
          '<isShowNextUsers>' +
          (record['isShowNextUsers'] ? 1 : 0) +
          '</isShowNextUsers>' +
          '<isBtnSaveShow>' +
          (record['isBtnSaveShow'] ? 1 : 0) +
          '</isBtnSaveShow>' +
          '<redirectUrl>' +
          record['redirectUrl'] +
          '</redirectUrl><nodeScript>' +
          xmlEncode(dataRef.value['nodeScript']) +
          '</nodeScript><isModuleFilter>' +
          (record['isModuleFilter'] ? 1 : '') +
          '</isModuleFilter><branchMode>' +
          record['branchMode'] +
          '</branchMode><deptField>' +
          (isArray(record['deptField']) ? record['deptField'].join(',') : record['deptField']) +
          '</deptField><canSelUserWhenReturned>' +
          (record['canSelUserWhenReturned'] ? record['canSelUserWhenReturned'] : 'false') +
          '</canSelUserWhenReturned></action>',
      ),
    );
    let newNode: any = null;
    if (typeof document.importNode == 'function') {
      newNode = document.importNode($elem.find('action').get(0), true);
    } else {
      newNode = $elem.find('action').get(0);
    }
    console.log('newNode', newNode);
    $xml.find('actions').get(0)?.appendChild(newNode);

    console.log('makeSubFlowProp xml', $xml?.xml());
    if (!$xml[0]) return;
    useFlow.setFlowEdit({ ...useFlow.flowEdit, props: $xml?.xml() });
  }

  const [registerModalConfiguration, { openModal: openConfiguration }] = useModal();

  //配置
  const handleConfiguration = () => {
    openConfiguration(true, {
      fields: mockData.value,
      fieldsOfDept: fieldsOfDept.value,
      flowJson: $.myflow.getJson(),
      formCode: props.formCode,
    });
  };
  //配置回调
  const handleSuccessConfiguration = (mode) => {
    console.log('handleSuccessConfiguration mode', mode);
    if (mode == 0) {
      dataRef.value.isImgComb = false;
    } else {
      dataRef.value.isImgComb = true;
    }
  };

  // 设计器
  const [registerModalDesignIframe, { openModal: openDesignIframe, closeModal }] = useModal();

  //设计器打开
  const handleDesignIframe = () => {
    // const record = getFieldsValue();
    openDesignIframe(true, {
      formCode: props.formCode,
      scriptStr: dataRef.value.nodeScript, //record.nodeScript,
    });
  };
  //设计器回调
  const handleSuccessDesignIframe = (value) => {
    dataRef.value.nodeScript = value;
    // setFieldsValue({ nodeScript: dataRef.value.nodeScript });
  };

  const userStore = useUserStore();
  const ifrmRef = ref<any>(null);
  let ideUrl = 'script_frame.jsp';
  const onMessage = (e) => {
    var d = e.data;
    var data = d.data;
    var type = d.type;
    if (type == 'setScript') {
      console.log('onMessage data', data);
      dataRef.value.nodeScript = data;
      // setFieldsValue({ nodeScript: dataRef.value.nodeScript });
      if (d.cwsToken != null) {
        let cwsToken = d.cwsToken;
        ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
      }
      closeModal();
    } else if (type == 'getScript') {
      let serverInfo = userStore.getServerInfo;
      console.log('getScript scriptStr.value=', dataRef.value.nodeScript);
      let data = {
        type: 'openerScript',
        version: serverInfo.version,
        spVersion: serverInfo.spVersion,
        scene: 'flow.node',
        data: dataRef.value.nodeScript ? dataRef.value.nodeScript : '',
      };
      // window.postMessage(data, '*');
      unref(ifrmRef)?.doPostMessage(data);
    } else if (type == 'setCwsToken') {
      let cwsToken = d.cwsToken;
      ideUrl = 'script_frame.jsp?cwsToken=' + cwsToken;
    }
  };

  if (window.addEventListener) {
    // all browsers except IE before version 9
    window.addEventListener('message', onMessage, false);
  }
  onUnmounted(() => {
    console.log('NodeEdit-onUnmounted');
    window.removeEventListener('message', onMessage, false);
  });

  const handleClickMenu = (value, col) => {
    const record = getFieldsValue();
    if (!record[col]) {
      record[col] = '';
    }
    record[col] += value.indexOf('$') == 0 ? value : '{$' + value + '}';
    setFieldsValue({ [col]: record[col] });
  };

  const readonlyAceEditor = computed(() => isScriptEditable.value > 0);

  const isActionForm = computed(() => {
    return (
      privActionForm.value != '' &&
      (privActionForm.value != props.formCode ||
        (curActionForm.value && privActionForm.value != curActionForm.value))
    );
  });

  const [registerSelectAllModal, { openModal: openModalSelectAll }] = useModal();
  //删除选择的人
  const handleDeleteUser = (record) => {
    console.log('handleDeleteUser', record);
    dataRef.value.ActionApplicantAssignedUsers = dataRef.value.ActionApplicantAssignedUsers.filter(
      (item) => item != record,
    );
  };
  //选人
  const handleSelectUserAdd = () => {
    // const record = getFieldsValue();
    openModalSelectAll(true, {
      users: [],
    });
  };
  //选人回调
  const handleSuccessSelectAllModal = (users) => {
    if (users && users.length) {
      const keys = dataRef.value.ActionApplicantAssignedUsers.map((el) => el.userName);
      users.forEach((item) => {
        if (!keys.includes(item.key)) {
          dataRef.value.ActionApplicantAssignedUsers.push({
            userName: item.key,
            realName: item.title,
          });
        }
      });
    }
  };

  const handleChangeActionApplicantSelScope = () => {
    dataRef.value.ActionApplicantAssignedUsers = [];
    dataRef.value.ActionApplicantAssignedRoles = [];
  };
</script>

<style lang="less" scoped>
  // :deep(.ant-divider) {
  //   margin: 8px 0;
  // }
  .ant-divider {
    margin: 0;

    :deep(.ant-divider-inner-text) {
      padding: 0 5px;
    }
  }

  :deep(.ant-tree-switcher) {
    width: 0;
  }
</style>
